﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Caching;
using Twipler.App.DataDoc;
using Twipler.App.Machine;

namespace Twipler.App.Render.Tree
{
    public class DocItem : AbstractItem
    {
        private AbstractItem _renderItem;
        private String _name;
        private StaticMethodCall _staticCall;
        private TimeSpan? _cacheDuration;
        
        public override List<AbstractItem> Children { get { return new List<AbstractItem> {_renderItem}; } }

        public static DocItem Create(AbstractItem containedItem, string name, StaticMethodCall staticCall, TimeSpan? cacheDuration)
        {
            return new DocItem()
                       {
                           _renderItem = containedItem,
                           _name = name,
                           _staticCall = staticCall,
                           _cacheDuration = cacheDuration
                       };
        }

        public override void Render(System.Text.StringBuilder html, App.Machine.Environment environment)
        {
            IDataDoc doc = null;

            if (_cacheDuration.HasValue && HttpContext.Current.Cache[Current.PrivateUniqueSecret + _staticCall] != null)
                doc = HttpContext.Current.Cache[Current.PrivateUniqueSecret + _staticCall] as IDataDoc;
            
            if (doc == null)
                doc = _staticCall.Invoke(environment) as IDataDoc;

            if (_cacheDuration.HasValue && doc != null)
                HttpContext.Current.Cache.Add(Current.PrivateUniqueSecret + _staticCall, doc, null,
                                              DateTime.Now.Add(_cacheDuration.Value),
                                              Cache.NoSlidingExpiration,
                                              CacheItemPriority.Low, null);
            
            object variable = environment.Variables_Descope(_name);
            environment.Variables_Add(_name, doc);

            _renderItem.Render(html, environment);

            environment.Variables_Restore(_name, variable);
        }

    }

}